﻿using JUtil;
using JUtil.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeGen
{
    public abstract class CSharpFileGenerator
    {
        #region Indent Handling
        protected virtual string IndentContent { get { return "	"; } }

        private int IndentCount = 0;
        
        protected string StartBlock
        {
            get
            {
                string result = IndentString("{\n");

                IndentCount++;

                return result;
            }
        }

        protected string EndBlock
        {
            get
            {
                IndentCount--;

                string result = IndentString("}\n");

                return result;
            }
        }

        protected string IndentString(string str)
        {
            string result = string.Empty;

            for (int i = 0; i < IndentCount; i++)
                result += IndentContent;

            result += str;

            return result;
        }
        #endregion

        protected abstract List<string> GetUsingNameSpaces();

        protected abstract string GetDeclareNameSpaces();

        private void ExportUsingNameSpace(StringBuilder sb)
        {
            foreach (string usingNameSpace in GetUsingNameSpaces())
            {
                string strUsing = string.Format("using {0};", usingNameSpace);

                sb.Append(strUsing);
                sb.Append("\n");
            }
            sb.Append("\n");
        }

        private void ExportNameSpace(StringBuilder sb)
        {
            string declareNS = string.Format("namespace {0}", GetDeclareNameSpaces());
            sb.Append(IndentString(declareNS));
            sb.Append("\n");

            sb.Append(StartBlock);

            ExportClass(sb);

            sb.Append(EndBlock);
        }

        //protected virtual void ExportClass(StringBuilder sb)
        //{
        //    string declareClass = string.Format("class {0}", GetDeclareClass());
        //    sb.Append(IndentString(declareClass));
        //    sb.Append("\n");

        //    sb.Append(StartBlock);

        //    //ExportProperty(sb);

        //    sb.Append(EndBlock);
        //}

        protected abstract void ExportClass(StringBuilder sb);

        public void Export(string filepath)
        {
            JUtil.Path.File.Delete(filepath);

            StringBuilder sb = new StringBuilder();

            ExportUsingNameSpace(sb);

            ExportNameSpace(sb);

            sb.ToString().SaveAs(filepath);
        }

        
    } // end of CSharpFileGenerator
}
